//Titanium.include('suds.js');
var EMAIL = "vinicius@open.inf.br";
var HOST = "http://201.21.208.110:8080/WebPervasivo"; 
//var HOST = "http://201.21.208.110:8080/WebPervasivo"; 
//var HOST = "http://127.0.0.1:8082"; 

var PASSWORD = "123456";
var CONECTADO = 0;
ERROR_GPS=0;


//FUNCAO QUE VAI ATUALIZAR A POSICAO QUANDO CONECTADO


var atualizaPosicaoGPS = function() {
	//alert("triger acionado");
	Titanium.API.warn('tigger acionado');
	if (CONECTADO == 1 ){
		var cur_longitude=0, cur_latitude=0;
		var xhr=Titanium.Network.createHTTPClient();    
		xhr.open("POST",HOST+"/RefreshGps");//ADD your URL
		xhr.setRequestHeader("content-type", "application/json");
		//PEGANDO GPS


		Titanium.Geolocation.getCurrentPosition(function(e){
			if (e.error) {
				if(ERROR_GPS==0) alert("Erro GPS");
				ERROR_GPS=1;
    			return;

    		}
	        cur_longitude = e.coords.longitude;                     
	        cur_latitude = e.coords.latitude;
	 
	 
	        // Ti.API.warn(mycoordsVector);
	 
    	});

		
		
		/*
		var param={ "email":EMAIL,"lat":cur_latitude,"long":cur_longitude};
		 
		xhr.send(param);
		 
		xhr.onload = function(){
		 if(this.status == '200'){
		    if(this.readyState == 4){
		      var response=JSON.parse(this.responseText);
		      if (response.error ="1"){
		      	alert("Erro de conexao " +response.status);
		      }else{
		      	//CONECTADO = 1;
		      	alert("mandou1");
		      }
		      
		    }else{
		      alert('HTTP Ready State != 4');
		    }           
		 }else{
		    alert('HTTp Error Response Status Code = '+this.status);
		    alert("Error =>"+this.response);
		 }              
		};
		*/
	}
	
	
}


function getServicesOnPlace(id){
	
	var xhr=Titanium.Network.createHTTPClient();    
	xhr.onerror = function(e){ 
		alert('Bad Sever =>'+e.error);
	};
	 
	xhr.open("POST",HOST+"/getServicesOnPlace");//ADD your URL
	//xhr.setRequestHeader("content-type", "application/json");
	var param={ "id_place":id };
	 
	//Ti.API.info('Params'+JSON.stringify(param));
	xhr.send(param);
	 
	xhr.onload = function(){
	 if(this.status == '200'){
	    if(this.readyState == 4){
	      var response=JSON.parse(this.responseText);
	      if (response.error =="1"){
	      	alert(response.status);
	      }else{
	      	   if (response.services && response.services.length>0) {
			   //var result = results.item(0);
			   //winPlace.title=response.nome;
			   var data = new Array();
			   for (var i = 0; i < response.services.length; i++) {
			   	var row1 = Titanium.UI.createTableViewRow({hasChild:false,title:' '+response.services[i].name , id:''+response.services[i].id});
			   var picker = Titanium.UI.createPicker({
					right: 5,
					width: 'auto',
				});
				
				
				var datap = new Array();
				for (var j = 0; j < response.services[i].options.length; j++) {
					datap[j]=Titanium.UI.createPickerRow({title:''+response.services[i].options[j].valueString , id:''+response.services[i].options[j].valueInt });
				}
				//datap[1]=Titanium.UI.createPickerRow({title:''+response[i].values[j].value});
				picker.add(datap);
		
				var label1 = Titanium.UI.createLabel({
				    color:'#999',
				    text:response.services[i].name + '  atual:' + response.services[i].current.valueString + '  padrão:' + response.services[i].current.valueString + '  padrão:' ,
				    font:{fontSize:13,fontWeight:'normal', fontFamily:'Arial'},
				    left:5
				}); 


				row1.add(label1);
				row1.add(picker);

			      // data[i+2] = Ti.UI.createTableViewRow({hasChild:true,title:' '+response[i].nome , id:''+response[i].id})
			      data[i]= row1;
		}	
			    tableWinPlaces.data = data;        	
			 }

	      }
	      
	    }else{
	      alert('HTTP Ready State != 4');
	    }           
	 }else{
	    alert('HTTp Error Response Status Code = '+this.status);
	    alert("Error =>"+this.response);
	 }              
	};
		
}




		
function getPlacesAround(){
	
	var xhr=Titanium.Network.createHTTPClient();    
	xhr.onerror = function(e){ 
		alert('Bad Sever =>'+e.error);
	};
	 
	xhr.open("POST",HOST+"/getPlacesAround");//ADD your URL
	//xhr.setRequestHeader("content-type", "application/json");
	var param={ "email":EMAIL,"Param2":"PARAM2","PARAM3":"PARAM3" };
	 
	//Ti.API.info('Params'+JSON.stringify(param));
	xhr.send(param);
	 
	xhr.onload = function(){
	 if(this.status == '200'){
	    if(this.readyState == 4){
	      var response=JSON.parse(this.responseText);
	      if (response.error =="1"){
	      	alert(response.status);
	      }else{
	      	   if (response && response.length>0) {
			   //var result = results.item(0);
			   var data = new Array();
			   for (var i = 0; i < response.length; i++) {
			       data[i+2] = Ti.UI.createTableViewRow({hasChild:true,title:' '+response[i].nome , id:''+response[i].id})
		}	
			    tablePlaces.data = data;        	
			 }

	      }
	      
	    }else{
	      alert('HTTP Ready State != 4');
	    }           
	 }else{
	    alert('HTTp Error Response Status Code = '+this.status);
	    alert("Error =>"+this.response);
	 }              
	};
		
}

		
function conecta(){
	
	var xhr=Titanium.Network.createHTTPClient();    
	xhr.onerror = function(e){ 
		alert('Bad Sever =>'+e.error);
	};
	 
	xhr.open("POST",HOST+"/Login");//ADD your URL
	//xhr.setRequestHeader("content-type", "application/json");
	var param={ "email":EMAIL,"Param2":"PARAM2","PARAM3":"PARAM3" };
	 
	//Ti.API.info('Params'+JSON.stringify(param));
	xhr.send(param);
	 
	xhr.onload = function(){
	 if(this.status == '200'){
	    if(this.readyState == 4){
	      var response=JSON.parse(this.responseText);
	      if (response.error =="1"){
	      	alert(response.status);
	      }else{
	      	CONECTADO = 1;
	      	alert("conectado");
	      	setInterval(atualizaPosicaoGPS, 10000);

	      }
	      
	    }else{
	      alert('HTTP Ready State != 4');
	    }           
	 }else{
	    alert('HTTp Error Response Status Code = '+this.status);
	    alert("Error =>"+this.response);
	 }              
	};
		
}


/*
function atualizaTable(id){	
	var data = new Array();
	tableview.data = data;
	var url = "http://wspervasivo.dyndns.biz:8082/wspervasivo.asmx";
		var callparams = {
		    id_usuario: 1,
		    id_ambiente: id,
		    banco: 1
		};
		var suds = new SudsClient({
		    endpoint: url,
		    targetNamespace: 'http://tempuri.org/'
		});		
		suds.invoke('ListaHistoricoUsuarios', callparams, function(xmlDoc) {
			var results = xmlDoc.documentElement.getElementsByTagName('DataEntrada');
			var results2 = xmlDoc.documentElement.getElementsByTagName('DescUsuario');

			        
			if (results && results.length>0) {
			   //var result = results.item(0);
			   var data = new Array();
			   for (var i = 0; i < results.length; i++) {
			       data[i] = Ti.UI.createTableViewRow({hasChild:true,title:' '+results.item(i).text+' '+results2.item(i).text});
				}	
			    tableview.data = data;        	
			 }
		});
	
}

function entra(id){	
	var data = new Array();
	tableview.data = data;
	var url = "http://wspervasivo.dyndns.biz:8082/wspervasivo.asmx";
		var callparams = {
		    id_usuario: 1,
		    id_ambiente: id,
		    banco: 1
		};
		var suds = new SudsClient({
		    endpoint: url,
		    targetNamespace: 'http://tempuri.org/'
		});		
		suds.invoke('RegistraPresenca', callparams, function(xmlDoc) {
			var results = xmlDoc.documentElement.getElementsByTagName('DataEntrada');
			var results2 = xmlDoc.documentElement.getElementsByTagName('DescUsuario');

			        
			atualizaTable(AMBIENTE);
		});
	
}
function atualizaAmbiente(){	
	var url = "http://wspervasivo.dyndns.biz:8082/wspervasivo.asmx";
		var callparams = {
	
		    banco: 1
		};
		var suds = new SudsClient({
		    endpoint: url,
		    targetNamespace: 'http://tempuri.org/'
		});		
		suds.invoke('ListaAmbientes', callparams, function(xmlDoc) {
			var results = xmlDoc.documentElement.getElementsByTagName('Descricao');        
			if (results && results.length>0) {
			   //var result = results.item(0);
			   var data = new Array();
			   for (var i = 0; i < results.length; i++) {
			       data[i] = Titanium.UI.createPickerRow({title:' '+results.item(i).text});
				}	
			    picker.add(data);        	
			 }
		});
	
}
*/